package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.login.LoginService;
import com.sh.d1.gameserver.model.User;
import com.sh.d1.gameserver.model.UserManager;
import com.sh.d1.gameserver.msg.GameMsgProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 选择英雄指令处理器
 */
public class SelectHeroCmdHandler implements ICmdHandler<GameMsgProtocol.SelectHeroCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(SelectHeroCmdHandler.class);

    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.SelectHeroCmd cmd) {
        if (null == ctx ||
            null == cmd) {
            return;
        }

        // 先拿到用户 Id
        int userId = ctx.getFromUserId();

        if (userId <= 0) {
            return;
        }

        // 获取英雄对象
        User existUser = UserManager.getByUserId(userId);
        if (null == existUser) {
            LOGGER.info("用户不存在, userId = {}", userId);
            return;
        }

        // 获取英雄形象
        final String heroAvatar = cmd.getHeroAvatar();
        // 更新英雄形象
        LoginService.getInstance().updateHeroAvatarByUserId(userId, heroAvatar, (succezz) -> {
            if (!succezz) {
                LOGGER.error("修改英雄形象失败, userId = {}", userId);
                return null;
            }

            existUser.heroAvatar = heroAvatar;

            GameMsgProtocol.SelectHeroResult.Builder resultBuilder = GameMsgProtocol.SelectHeroResult.newBuilder();
            resultBuilder.setHeroAvatar(heroAvatar);

            // 构建结果并发送
            GameMsgProtocol.SelectHeroResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);

            return null;
        });
    }
}
